package com.fqxiny.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fqxiny.lease.common.constant.RedisConstant;
import com.fqxiny.lease.common.exception.UpException;
import com.fqxiny.lease.common.result.ResultCodeEnum;
import com.fqxiny.lease.common.utils.JWTUtil;
import com.fqxiny.lease.model.entity.SystemUser;
import com.fqxiny.lease.web.admin.mapper.SystemUserMapper;
import com.fqxiny.lease.web.admin.service.LoginService;
import com.fqxiny.lease.web.admin.vo.login.CaptchaVo;
import com.fqxiny.lease.web.admin.vo.login.LoginVo;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import jakarta.annotation.Resource;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author : 戚欣扬
 * @code :
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Resource
    SystemUserMapper systemUsermapper;

    @Override
    public CaptchaVo getCaptcha() {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 3);
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        String key = RedisConstant.APP_LOGIN_PREFIX + UUID.randomUUID().toString();
        String value = specCaptcha.text();
        redisTemplate.opsForValue().set(key,value,RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC, TimeUnit.SECONDS);
        String picture = specCaptcha.toBase64();
        return new CaptchaVo(key,picture);
    }

    @Override
    public String login(LoginVo loginVo) {
        String captchaKey = loginVo.getCaptchaKey();
        String value = (String) redisTemplate.opsForValue().get(captchaKey);
        if(value == null){
            throw new UpException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        if(!value.equalsIgnoreCase(loginVo.getCaptchaCode())){
            throw  new UpException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        String sha256Hex = DigestUtils.sha256Hex(loginVo.getPassword());
        SystemUser systemUser = systemUsermapper.selectOne(
                Wrappers.lambdaQuery(SystemUser.class)
                        .eq(SystemUser::getUsername, loginVo.getUsername())
                        .eq(SystemUser::getPassword, sha256Hex)
        );
        if(systemUser == null){
            throw new UpException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        if(systemUser.getStatus().getCode()!=1){
            throw new UpException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        return JWTUtil.createToken(systemUser.getId(), systemUser.getUsername());
    }
}


